import React,{Component} from 'react';
import {Button, Form, Input, Select, Spin, DatePicker, Icon, Row, Col} from 'antd';
import {messages} from "share/common";
import VoyageForm from './voyage-form';
import moment from 'moment';
import 'styles/supplier-management/air-ticket-quotation/air-ticket-quotation-detail.scss';
const Option = Select.Option;
const FormItem = Form.Item;
import AirTicketServer from './air-ticket-server';

@Form.create()
class AddQuotationContent extends Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      hds: [{key: 'hd0'}],
      baseData: {},
      isDetail: false,
    }
    this.voyageRefs = [];
  }

  componentWillMount(){
    const {params} = this.props;
    if(params.id){
      this.setState({baseData: params, isDetail: true})
      AirTicketServer(this).quotationHD(params.id).then(res => {
        if(res.status === 200){
          let hds = res.data.body.map(item => {
            return {
              key: `hd${item.segmentNo}`,
              value: item
            }
          })
          this.setState({hds})
        }
      })
    }
  }

  onCancelEdit = () => {
    this.props.close();
  }

  onSubmitEdit = () => {
    const {isDetail} = this.state;
    if(isDetail){
      this.onCancelEdit();
      return;
    }
    for(let i=0; i < this.voyageRefs.length;i++){
      this.voyageRefs[i].onCheckParams();
    }
    setTimeout(()=>{
      this.props.form.validateFieldsAndScroll((err, values) => {
        if(!err){
          let params = Object.assign({}, values);
          params.latestConfirmDate = values.latestConfirmDate.format('YYYY-MM-DD HH:mm:ss');
          params.journeys = [];
          for(let key in params){
            if(key.indexOf('hd') > -1){
              params.journeys.push(params[key]);
              delete params[key];
            }
          }
          params.rfpId = this.props.params.rfpId;
          AirTicketServer(this).quotationAdd(params).then(res => {
            if(res.status === 200){
              this.props.close('update');
            }
          })
        }
      })
    })
  }

  onAddVoyage = () => {
    const {hds} = this.state;
    hds.push({key: `hd${hds.length}`});
    this.setState({hds});
  }

  onVoyageFormRef = (voyageRef, index) => {
    this.voyageRefs[index] = voyageRef;
  }

  onDeleteHd = (index) => {
    const {hds} = this.state;
    hds.splice(index, 1);
    this.setState({hds});
  }

  onBlurNumber = (key) => {
    setTimeout(()=>{
      let value = this.props.form.getFieldsValue();
      let num = parseFloat(value[key]);
      if(num < 0){
        this.props.form.setFieldsValue({[key]: 0});
      }
    })
  }

  render(){
    const {loading, hds, baseData, isDetail} = this.state;
    const { getFieldDecorator } = this.props.form;
    let span = 12;
    let rules = [{
      required: true,
      message: messages('supplier.key612')/*必填*/
    }]
    let itemMargin = {
      marginBottom: 12
    }
    return (
      <div className='air-ticket-quotation-detail'>
        <Spin spinning={loading}>
          <Form layout='vertical'>
            <div className='form-title-voyage' style={{marginTop: 0}}>
              {messages('supplier.key543')/*航段*/}
            </div>
            {
              hds.map((item, index) => {
                return (
                  <FormItem
                    label={
                      <div className='hd-title'>
                        <span>{messages('supplier.key1043',{arg1: index+1})/*航段{arg1}*/}</span>
                        {
                          !isDetail && (
                            <Button disabled={index === 0} size='small' type='primary' onClick={()=>this.onDeleteHd(index)}>
                              {messages('common.delete')/*删除*/}
                            </Button>
                          )
                        }
                      </div>
                    }
                    style={itemMargin}
                  >
                    {
                      getFieldDecorator(item.key,{
                        initialValue: item.value || '',
                        rules: [{
                          required: true,
                          message: ' '
                        }]
                      })(
                        <VoyageForm isDetail={isDetail} onRef={this.onVoyageFormRef} voyageIndex={index}/>
                      )
                    }
                  </FormItem>
                )
              })
            }
            {
              !isDetail && (
                <Button style={{width: "100%", marginTop: 6}} type='dashed' onClick={this.onAddVoyage}>
                  <Icon type='plus'/>
                  增加航段
                </Button>
              )
            }
            <div className='form-title-voyage'>
              {messages('supplier.key330')/*价格信息*/}
            </div>
            <Row>
              <Col span={span}  style={{paddingRight: 20}}>
                <FormItem label={messages('supplier.key1044')/*票面总价*/} style={itemMargin}>
                  {
                    getFieldDecorator('totalTicketPrice',{
                      initialValue: baseData.totalTicketPrice || '',
                      rules
                    })(
                      <Input min={0} onBlur={()=>this.onBlurNumber('totalTicketPrice')} disabled={isDetail} addonBefore='CNY' type='number'/>
                    )
                  }
                </FormItem>
              </Col>
              <Col span={span}  style={{paddingLeft: 20}}>
                <FormItem label={messages('supplier.key1045')/*税费*/} style={itemMargin}>
                  {
                    getFieldDecorator('totalTax',{
                      initialValue: baseData.totalTax || '',
                      rules
                    })(
                      <Input min={0} onBlur={()=>this.onBlurNumber('totalTax')} disabled={isDetail} addonBefore='CNY' type='number'/>
                    )
                  }
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={span}  style={{paddingRight: 20}}>
                <FormItem label={messages('supplier.key407')/*服务费*/} style={itemMargin}>
                  {
                    getFieldDecorator('totalSupplierServiceFee',{
                      initialValue: baseData.totalSupplierServiceFee || '',
                      rules
                    })(
                      <Input min={0} onBlur={()=>this.onBlurNumber('totalSupplierServiceFee')} disabled={isDetail} addonBefore='CNY' type='number'/>
                    )
                  }
                </FormItem>
              </Col>
              <Col span={span}  style={{paddingLeft: 20}}>
                <FormItem label={messages('supplier.key331')/*订单总价*/} style={itemMargin}>
                  {
                    getFieldDecorator('totalAmount',{
                      initialValue: baseData.totalAmount || '',
                      rules
                    })(
                      <Input min={0} onBlur={()=>this.onBlurNumber('totalAmount')} disabled={isDetail} addonBefore='CNY' type='number'/>
                    )
                  }
                </FormItem>
              </Col>
            </Row>
            <div className='form-title-voyage'>
              {messages('supplier.key341')/*其他信息*/}
            </div>
            <Row>
              <Col span={span}  style={{paddingRight: 20}}>
                <FormItem label={messages('supplier.key1046')/*方案介绍*/} style={itemMargin}>
                  {
                    getFieldDecorator('title',{
                      initialValue: baseData.title || '',
                      rules
                    })(
                      <Input disabled={isDetail} maxLength={10} placeholder={messages('supplier.key1076')/*最大长度10*/}/>
                    )
                  }
                </FormItem>
              </Col>
              <Col span={span}  style={{paddingLeft: 20}}>
                <FormItem label={messages('supplier.key1047')/*最晚确认时间*/} style={itemMargin}>
                  {
                    getFieldDecorator('latestConfirmDate',{
                      initialValue: baseData.latestConfirmDate ? moment(baseData.latestConfirmDate) : null,
                      rules
                    })(
                      <DatePicker style={{width: '58%'}} showTime format='YYYY-MM-DD HH:mm:ss' disabled={isDetail}/>
                    )
                  }
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={24}  style={{paddingRight: 20}} style={{width: 'calc(47% + 212px)'}}>
                <FormItem label={messages('supplier.key1048')/*方案备注*/} style={itemMargin}>
                  {
                    getFieldDecorator('remark',{
                      initialValue: baseData.remark || '',
                      rules
                    })(
                      <Input.TextArea disabled={isDetail} />
                    )
                  }
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Spin>
        <br/><br/><br/><br/>
        <div className='affix-bottom'>
          <Button type="primary"  onClick={this.onSubmitEdit} loading={loading}>
            {messages('common.ok')/*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </div>
    )
  }
}

export default AddQuotationContent;
